﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mani.Common.WorkflowEngine;

namespace RastinArgham.CRM.Business
{
    public class ProductOrderWorkflow : WorkflowBasic
    {
        public override Guid TypeId
        {
            get { return new Guid("8D97C974-D86B-43C5-A2CF-46F765912C6D"); }
        }

        protected override void InitializeStateManager()
        {
            WorkflowState stInitial = base.StateEngine.CreateState(10, "سفارش اولیه");
            WorkflowState stWaitingForInvoice = base.StateEngine.CreateState(20, "منتظر تولید فاکتور");
            WorkflowState stDeliveryToCustomer = base.StateEngine.CreateState(30, "منتظر تحویل به مشترک");
            WorkflowState stInCustomerUse = base.StateEngine.CreateState(40, "در اختیار کاربر");

            // This State is hardcoded in Contact and Order Entity (GetUsername and SubId Functions)
            WorkflowState stCancel = base.StateEngine.CreateState(50, "انصراف", new WorkflowStateEnter(releaseStockItem));

            stInitial.AddNewTransition("تایید سفارش", stWaitingForInvoice, new WorkflowGuard(CheckStockItemAssigned), null);
            stInitial.AddNewTransition("انصراف", stCancel, null, new WorkflowAction(releaseStockItem));
            
            stWaitingForInvoice.AddNewTransition("صدور فاکتور", stDeliveryToCustomer, null, null);
            stWaitingForInvoice.AddNewTransition("انصراف", stCancel, null, new WorkflowAction(releaseStockItem));

            stDeliveryToCustomer.AddNewTransition("تحویل شد", stInCustomerUse);
            stDeliveryToCustomer.AddNewTransition("انصراف", stCancel, null, new WorkflowAction(releaseStockItem));

            stInCustomerUse.AddNewTransition("انصراف", stCancel, null, new WorkflowAction(releaseStockItem));

            base.StateEngine.SetInitialState(stInitial);
            base.OnBasePersisted += new WorkflowPersisted(persistOrderWorkflow);
        }

        private void persistOrderWorkflow()
        {
            CRMRepository repo = new CRMRepository();
            Order o = repo.GetOrderById(this.ExternalId);
            o.LastUpdate = DateTime.Now;
            o.WorkflowStateId = this.StateId;
            
            if (this.lastOperatorId.HasValue)
                o.OperatorId = this.lastOperatorId.Value;

            repo.Save();
        }

        protected override void InitializeDataDictionary()
        {
        }

        private WorkflowGuardResult CheckStockItemAssigned()
        {
            CRMRepository crmRepository = new CRMRepository();
            Order o = crmRepository.GetOrderById(this.ExternalId);

            if (o.StockItems.Count == 0)
                return new WorkflowGuardResult("برای تایید سفارش باید سریال کالای سفارشی مشخص شود");

            foreach (var s in o.StockItems)
            {
                if (String.IsNullOrEmpty(s.SubID) || String.IsNullOrEmpty(s.PaymentCode) || s.SubID == "0" || s.PaymentCode == "0")
                    return new WorkflowGuardResult("برای تایید سفارش پر کردن کد پرداخت و شناسه اشتراک کالا الزامی می باشد ");    
            }
            
            return WorkflowGuardResult.Success;
        }

        private void releaseStockItem()
        {
            CRMRepository crmRepository = new CRMRepository();
            StockItem s = crmRepository.GetStockItemsByOrderId(base.ExternalId).FirstOrDefault();

            if (s == null)
                return;

            s.Status = (int)StockItemStates.InStock;
            s.OperatorId = this.lastOperatorId.Value;
            s.LastUpdate = DateTime.Now;
            s.OrderId = null;

            crmRepository.Save();
        }
    }
}
